package com.atguigu.tingshu.user.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.server.HttpServerRequest;
import com.atguigu.tingshu.common.login.GuiguLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Tag(name = "微信授权登录接口")
@RestController
@RequestMapping("/api/user/wxLogin")
@Slf4j
public class WxLoginApiController {

    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("/wxLogin/{code}")
    @Operation(summary = "小程序授权登录")
    public Result<Map<String, String>> wxLoginGetToken(@PathVariable String code){

        Map<String, String> map = userInfoService.wxLoginGetToken(code);


        return Result.ok(map);
    }


    @GuiguLogin(required = true)
    @GetMapping("/getUserInfo")
    @Operation(summary = "获取登录用户信息")
    public Result<UserInfoVo> getUserInfo(){

        Long userId = AuthContextHolder.getUserId();
        UserInfo userInfo = userInfoService.getById(userId);
        if (userInfo == null){
            return null;
        }
        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class);

        return Result.ok(userInfoVo);
    }

    @GuiguLogin
    @PostMapping("/updateUser")
    @Operation(summary = "更新用户信息")
    public Result updateUser(@RequestBody UserInfoVo userInfoVo){

        UserInfo userInfo = new UserInfo();

        userInfo.setId(AuthContextHolder.getUserId());
        userInfo.setNickname(userInfoVo.getNickname());
        userInfo.setAvatarUrl(userInfoVo.getAvatarUrl());


        userInfoService.updateById(userInfo);

        return Result.ok();
    }

}
